package com.itheima.controller;

import com.itheima.pojo.Emp;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

@Slf4j
@RequestMapping("/emps")
@RestController
public class EmpController {
    @Autowired
    private EmpService empService;

    /**
     * 分页查询+条件
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping
    public Result page(String name, Short gender,
                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer pageSize){
        log.info("分页查询员工，page={}, pageSize={}, name={}, gender={},begin={},end={}",
                page, pageSize, name, gender, begin, end);
        //1.调用service的分页方法，获取PageBean数据
        PageBean pageBean = empService.page(page, pageSize, name, gender, begin, end);

        //2.返回结果
        return Result.success(pageBean);
    }

    /**
     * 删除员工
     * @param ids
     * @return
     */
    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids){
        log.info("删除员工，ids={}",ids);
        //调用service的方法，进行删除
        empService.delete(ids);

        //响应
        return Result.success();
    }

    /**
     * 新增员工
     * @param emp
     * @return
     */
    @PostMapping
    public Result save(@RequestBody Emp emp){
        log.info("新增员工：emp={}", emp);
        //1.调用service方法，保存数据
        empService.save(emp);
        //2.响应
        return Result.success();
    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        log.info("查询员工：id={}", id);
        //1.调用service 获取
        Emp emp = empService.getById(id);
        //2.返回数据
        return Result.success(emp);
    }

    /**
     * 更新员工
     * @param emp
     * @return
     */
    @PutMapping
    public Result update(@RequestBody Emp emp){
        log.info("查询员工：emp={}", emp);
        //1.调用service，更新数据
        empService.update(emp);
        //2.返回结果
        return Result.success();
    }
}
